var express = require("express");
var router = express.Router();
const JWT = require("../../utils/JWT");
const adminModel = require("../../models/adminModel");
const roleModel = require("../../models/roleModel")

// 登录
router.post("/login", (req, res) => {
  let { username, password } = req.body;
  adminModel
    .findOne({ username: username, password: password })
    .then((data) => {
      if (!data) {
        return res.json({
          code: "2002",
          msg: "用户名或密码错误",
          data: null,
        });
      } else {
        // 生成token(用户信息,有效时间7天)
        const token = JWT.generate(
          {
            _id: data._id,
            username: data.username,
          },
          "7d"
        );
        res.header("Authorization", token); //同时将token在响应头中返回给前端
        return res.json({
          code: 200,
          msg: "登录成功",
          data: {
            username: data.username,
            token: token,
          },
        });
      }
    })
    .catch((err) => {
      return res.json({
        code: "1001",
        msg: "数据库读取失败~~~",
        data: null,
      });
    });
});

// 获取用户信息
router.get("/admin/info/:username", (req, res) => {
  let username = req.params.username;
  adminModel
    .findOne({ username: username })
    .populate('roleId')
    .select({ _id: 0, _v: 0 })
    .then((data) => {
      if (data.length === 0) {
        return res.json({
          code: 200,
          msg: "用户信息为空",
          data: data,
        });
      }
      return res.json({
        code: 200,
        msg: "获取用户信息成功",
        data: data,
      });
    })
    .catch((err) => {
      res.status(500).json({ message: err.message });
    });
});

// 获取用户列表
router.get('/admin',(req,res) => {
  let {pageNo,pageSize} = req.query
  adminModel
  .find()
  .skip((pageNo - 1) * pageSize)
  .limit(pageSize)
  .then(data => {
    if(data.length === 0){
      return res.json({
        code: 200,
        msg: "用户信息为空",
        data: data,
      });
    }
    return res.json({
      code: 200,
      msg: "获取用户信息成功",
      data: data,
      total:data.length
    });
  })
  .catch((err) => {
    res.status(500).json({ message: err.message });
  });
})

// 修改
router.post('/admin/update',async(req,res) => {
  let {_id,roleId} = req.body
  let role = await roleModel.findById({_id:roleId})
  let roleName = role.roleName
  adminModel.updateOne({_id},{...req.body,roleName})
  .then((data) => {
    if (!data.acknowledged) {
      return res.json({
        code: -1,
        msg: "修改失败",
        data: null,
      });
    }
    return res.json({
      code: 200,
      msg: "修改成功~",
      data: null,
    });
  })
  .catch((err) => {
    res.status(500).json({ message: err.message });
  });
})

// 新增
router.post("/admin/add",async (req,res) => {
  let {roleId} = req.body
  let role = await roleModel.findById({_id:roleId})
  let roleName = role.roleName
  adminModel.create({...req.body,roleName})
  .then(data => {
    if (!data) {
      return res.json({
        code: -1,
        msg: "新增失败",
        data: null,
      });
    }
    return res.json({
      code: 200,
      msg: "新增成功",
      data: data,
    });
  })
  .catch((err) => {
    res.status(500).json({ message: err.message });
  });
})

// 删除
router.post('/admin/delete',(req,res) => {
  let {_id} = req.body
  adminModel.deleteOne({_id})
  .then(result => {
    if (result.deletedCount !== 0) {
      return res.json({
        code: 200,
        msg: "删除成功",
        data: null,
      });
    }
    return res.json({
      code: -1,
      msg: "删除失败",
      data: null,
    });
  })
  .catch((err) => {
    res.status(500).json({ message: err.message });
  });
})

// 搜索
router.get('/admin/search',(req,res) => {
  let {username} = req.query
  const regex = new RegExp(username);
  adminModel
  .find({username:regex})
  .then(data => {
    if (data.length === 0) {
      return res.json({
        code: 200,
        msg: "用户信息为空",
        data: data,
      });
    }
    return res.json({
      code: 200,
      msg: "查询成功",
      data: data,
      total:data.length
    });
  })
  .catch((err) => {
    res.status(500).json({ message: err.message });
  });
})

module.exports = router;
